package file;

import java.io.*;
import java.net.*;
import java.util.*;

public class FileReceiverServer {
    private static final int PORT = 12346;
    private static final String SAVE_DIRECTORY = "received_files/";

    public static void main(String[] args) {
        // 创建保存目录
        new File(SAVE_DIRECTORY).mkdirs();

        System.out.println("文件接收服务器正在启动...");
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器已启动，等待文件传输请求...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                new FileReceiverThread(clientSocket).start();
            }
        } catch (IOException e) {
            System.err.println("服务器异常: " + e.getMessage());
        }
    }

    private static class FileReceiverThread extends Thread {
        private Socket socket;

        public FileReceiverThread(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            String clientIP = socket.getInetAddress().getHostAddress();
            System.out.println("客户端连接: " + clientIP);

            try (DataInputStream dis = new DataInputStream(socket.getInputStream());
                 DataOutputStream dos = new DataOutputStream(socket.getOutputStream())) {

                // 接收文件名和大小
                String fileName = dis.readUTF();
                long fileSize = dis.readLong();

                System.out.println("接收文件: " + fileName + " (" + fileSize + " bytes) 来自 " + clientIP);

                // 创建文件输出流
                File outputFile = new File(SAVE_DIRECTORY + fileName);
                try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                    byte[] buffer = new byte[4096];
                    int read;
                    long remaining = fileSize;

                    while (remaining > 0 &&
                            (read = dis.read(buffer, 0, (int)Math.min(buffer.length, remaining))) != -1) {
                        fos.write(buffer, 0, read);
                        remaining -= read;
                    }
                }

                System.out.println("文件接收完成: " + outputFile.getAbsolutePath());
                dos.writeUTF("文件传输成功");

            } catch (IOException e) {
                System.err.println("文件接收错误: " + e.getMessage());
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}